import { defineStore } from 'pinia'
import { userApi } from '@/api/user'
import { domesticUserCenter } from 'ld-web-sdk';
import { ElMessage } from 'element-plus'
import successIcon from '@/assets/images/success-icon.png'

// 用户信息存储
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: '',
      nickname: '',
      portraiturl: '',
      role: ''
    },
    version: localStorage.getItem('version') || '',
    token: localStorage.getItem('token') || '',
    sign: localStorage.getItem('sign') || '',
    uid: localStorage.getItem('uid') || '',
    coin: 0,
    isLoggedIn: false
  }),

  getters: {
    // 获取用户角色
    getUserRole: (state) => state.userInfo.role,

    // 检查是否有权限
    hasPermission: (state) => (permission) => {
      // 这里可以根据实际需求实现权限检查逻辑
      return state.isLoggedIn
    }
  },

  actions: {
    // 登录
    login(userData) {
      this.userInfo = userData.userInfo
      this.token = userData.token
      this.sign = userData.sign
      this.uid = userData.uid
      this.isLoggedIn = true
      console.log(this.sign);
      console.log(this.uid);

      // 存储到本地
      localStorage.setItem('userInfo', JSON.stringify(userData.userInfo))
      localStorage.setItem('token', userData.token)
      localStorage.setItem('sign', userData.sign)
      localStorage.setItem('uid', userData.uid)

      // 获取用户云豆
      this.setCoin();
    },

    // 登出
    logout() {
      this.userInfo = {
        id: '',
        name: '',
        avatar: '',
        role: ''
      }
      this.token = ''
      this.sign = ''
      this.uid = ''
      this.coin = 0
      this.isLoggedIn = false

      // 清除本地存储
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')

      ElMessage({
        type: 'success',
        customClass: 'custom-success-message-icon',
        dangerouslyUseHTMLString: true,
        message: `<img src="${successIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">退出成功`,
        offset: 65
      })
    },

    // 从本地存储加载用户信息
    loadUserInfo() {
      const userInfo = localStorage.getItem('userInfo')
      const token = localStorage.getItem('token')

      if (userInfo && token) {
        this.userInfo = JSON.parse(userInfo)
        this.token = token
        this.isLoggedIn = true
      }
    },
    //获取用户信息-云豆 
    setCoin() {
      userApi.getUserInfo().then(response => {
        if (response && response.info) {
          this.coin = response.info.coin;
        }
      }).catch(error => {
      });
    },
    // 获取用户信息
    async RefreshUserInfo() {
      const userInfo = await domesticUserCenter.getLoginInfo()

      console.log("userInfo.....", userInfo);

      if (userInfo) {
        const userData = {
          userInfo: userInfo,
          token: userInfo.token,
          sign: userInfo.sign,
          uid: userInfo.uid,
        }
        this.login(userData)
      }
    }
  }
})